<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <th:block th:include="common/common_head :: commonHeader('采购申请录入')"/>
    <link th:href="@{/static/css/plugins/cropper/cropper.min.css}" rel="stylesheet">
    <link th:href="@{/static/css/custom/jquery.auto-complete.css}" rel="stylesheet">
</head>

<body class="gray-bg">

<div class="wrapper wrapper-content animated fadeInRight">
    <form class="form-horizontal" onsubmit="$('#vendorCode').blur();return false;" method="post"
          id="nproPurchRequestHeaderForm">
        <div class="row">
            <div class="form-group">
                <div class="col-sm-8" style="margin-left: 16px">
                    <input class="btn btn-primary" type="button" onclick="save()" value="保存">
                    <button class="btn btn-primary" type="button" onclick="Dialog.closeFrame(window.name)">取 消</button>
                </div>
            </div>
            <div>
                <div class="ibox float-e-margins">
                    <div class="ibox-content">
                        <div id="toolbar" class="btn-group">
                            <button type="button" class="btn btn-xs btn-link" onclick="addtr()">添加</button>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-bordered text-nowrap" id="para_table">
                                <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>采购申请编码</th>
                                    <th>采购申请行项目编码</th>
                                    <th>供应商编码</th>
                                    <th>供应商名称</th>
                                    <th>付款条件</th>

                                    <th>物料描述</th>
                                    <th>含税单价</th>
                                    <th>最小起订量</th>
                                    <th>货币</th>
                                    <th>税码</th>
                                    <th>购买量</th>

                                    <th>采购申请类型</th>

                                    <th>创建人</th>
                                    <th>申请部门</th>
                                    <th>科目类别</th>
                                    <th>采购组</th>
                                    <th>采购组织</th>
                                    <th>使用人</th>
                                    <th>工厂</th>
                                    <th>物料组</th>
                                    <th>申请数量</th>
                                    <th>计量单位</th>
                                    <th>需求日期</th>
                                    <!-- <th>交货日期</th> -->

                                    <th>总账科目</th>
                                    <th>成本中心</th>
                                    <th>内部订单号</th>
                                    <th>主资产号</th>
                                    <th>资产次级编号</th>
                                    <th>库存地点</th>
                                    <th>备注</th>
                                    <th></th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr th:each="SupplyGoodsEntityVO,itemStat : ${itemlist}"
                                    th:class="${itemStat.odd}?'odd':'even'">
                                    <td th:text="${itemStat.index+1}"></td>
                                    <td style="display:none"><input name="pkId" type="hidden"
                                                                    th:value="${SupplyGoodsEntityVO.pkId}"/></td>
                                    <td width='30px'><input readonly="readonly" id="purchRequestCode"
                                                            name='purchRequestCode'
                                                            th:value="${SupplyGoodsEntityVO.purchRequestCode}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='purchRequestItemCode'
                                                             name='purchRequestItemCode'
                                                             th:value="${SupplyGoodsEntityVO.purchRequestItemCode}"/>
                                    </td>

                                    <td width='110px'><input readonly="readonly" autofocus type='text' id="vendorCode"
                                                             name='vendorCode'
                                                             th:value="${SupplyGoodsEntityVO.vendorCode}"
                                                             th:indexval="${itemStat.index}"/></td>
                                    <!-- data-toggle='modal' data-target='#myModalVendor' onclick="show(this)"-->
                                    <td width='200px'><input readonly="readonly" autofocus type='text' id="vendorName"
                                                             name='vendorName'
                                                             th:value="${SupplyGoodsEntityVO.vendorName}"/></td>

                                    <td width='110px'><input readonly="readonly" autofocus type='text' id="payCondition"
                                                             name='payCondition'
                                                             th:value="${SupplyGoodsEntityVO.payCondition}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='materialDesc'
                                                             name='materialDesc'
                                                             th:value="${SupplyGoodsEntityVO.materialDesc}"
                                                             style="width: 300px"/></td>
                                    <!-- data-toggle='modal' data-target='#myModalGoods' onclick="fun(this)"-->
                                    <td width='110px'><input type='number' id='taxPrice' name='taxPrice'
                                                             th:value="${SupplyGoodsEntityVO.taxPrice}"/></td>
                                    <td width='110px'><input type='number' id='priceUnit' name='priceUnit'
                                                             th:value="${SupplyGoodsEntityVO.priceUnit}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='currency'
                                                             name='currency'
                                                             th:value="${SupplyGoodsEntityVO.currency}"/></td>
                                    <td width='110px'><select id="taxCode" name='taxCode'
                                                              th:data-val="${SupplyGoodsEntityVO.taxCode}"
                                                              sysDict='SDM'></select></td>
                                    <!-- 根据月度评分得出购买数量 -->
                                    <td width='110px'><input readonly="readonly" type='text' id='quantity'
                                                             name='quantity'
                                                             th:value="${SupplyGoodsEntityVO.applyQty}"/></td>

                                    <td width='110px'><input readonly="readonly" type='text' id='purchRequestType'
                                                             name='purchRequestType'
                                                             th:value="${SupplyGoodsEntityVO.purchRequestType}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id="createdBy"
                                                             name='createdBy'
                                                             th:value="${SupplyGoodsEntityVO.createdBy}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='purchRequestDept'
                                                             name='purchRequestDept'
                                                             th:value="${SupplyGoodsEntityVO.purchRequestDept}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='subjectCategory'
                                                             name='subjectCategory'
                                                             th:value="${SupplyGoodsEntityVO.subjectCategory}"/></td>
                                    <td width='110px'><select disabled id='purchGroup' name='purchGroup'
                                                              th:data-val="${SupplyGoodsEntityVO.purchGroup}"
                                                              sysDict='CGZ'></select></td>
                                    <td width='110px'><select disabled id='purchOrg' name='purchOrg'
                                                              th:data-val="${SupplyGoodsEntityVO.purchOrg}"
                                                              sysDict='CGZZ'></select></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='applier' name='applier'
                                                             th:value="${SupplyGoodsEntityVO.applier}"/></td>
                                    <td width='110px'><select disabled id='factory' name='factory'
                                                              th:data-val="${SupplyGoodsEntityVO.factory}"
                                                              sysDict='GC'></select></td>
                                    <td width='110px'><select disabled id='materialGroup' name='materialGroup'
                                                              th:data-val="${SupplyGoodsEntityVO.materialGroup}"
                                                              sysDict='WLZ'></select></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='applyQty'
                                                             name='applyQty'
                                                             th:value="${SupplyGoodsEntityVO.applyQty}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='measureUnit'
                                                             name='measureUnit'
                                                             th:value="${SupplyGoodsEntityVO.measureUnit}"/></td>
                                    <!-- <td width='110px'><select id='measureUnit' name='measureUnit' th:data-val="${SupplyGoodsEntityVO.measureUnit}" sysDict='JLDW'></select></td> -->
                                    <!--<td width='110px'><select disabled id='costCenter' name='costCenter' th:data-val="${SupplyGoodsEntityVO.costCenter}" sysDict='CBZX'></select></td>-->

                                    <!-- th:value="${SupplyGoodsEntityVO.requestDate}" -->
                                    <td width='110px'><input readonly="readonly" type='text' name='requestDate'
                                                             th:value="${#dates.format(SupplyGoodsEntityVO.requestDate,'yyyy-MM-dd')}"/>
                                    </td><!-- id='requestDate'-->
                                    <!-- <td width='110px'><input type='text' id='deliveryDate' name='deliveryDate' th:value="${#dates.format(SupplyGoodsEntityVO.deliveryDate,'yyyy-MM-dd')}" /></td> -->
                                    <!-- 行项目的id -->
                                    <!-- <td width='110px'><input type='hidden' id='npkId' name='npkId' th:value="${InquiryQuotationEntity.'npkId'}"/></td> -->
                                    <!-- npk_id -->
                                    <!-- quantity -->
                                    <!-- quotation_id -->
                                    <td width='110px'><input readonly="readonly" type='text' id='ledgerAccount'
                                                             name='ledgerAccount'
                                                             th:value="${SupplyGoodsEntityVO.ledgerAccount}"/></td>
                                    <td width='110px'><input disabled id='costCenter' name='costCenter'
                                                             th:value="${SupplyGoodsEntityVO.costCenter}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='internalOrderCode'
                                                             name='internalOrderCode'
                                                             th:value="${SupplyGoodsEntityVO.internalOrderCode}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='mainAssetsCode'
                                                             name='mainAssetsCode'
                                                             th:value="${SupplyGoodsEntityVO.mainAssetsCode}"/></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='assetsSencondCode'
                                                             name='assetsSencondCode'
                                                             th:value="${SupplyGoodsEntityVO.assetsSencondCode}"/></td>

                                    <td width='110px'><select id='storageLocation' name='storageLocation'
                                                              th:data-val="${SupplyGoodsEntityVO.storageLocation}"
                                                              sysDict='KCDD' emptyFirst="true"></select></td>
                                    <td width='110px'><input readonly="readonly" type='text' id='remark' name='remark'
                                                             th:value="${SupplyGoodsEntityVO.remark}"/></td>
                                    <td style="display:none"><input readonly="readonly" type='text'
                                                                    name='deliveryAddress'
                                                                    th:value="${SupplyGoodsEntityVO.deliveryAddress}"/>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<!-- 从历史订单数据里面检索 -->
<div class="modal fade" id="myModalGoods" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document" style="width:70%">
        <div class="modal-content" style="height:700px">
            <form id="ordelForm" th:action="@{/order_item/findByName}" class="form-inline">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">历史订单数据</h4>
                </div>
                <!-- <input type="hidden" name="materialCode" id="materialCode" /> -->
                <div class="modal-body" style="height:90%;width:85%;overflow:auto">
                    <div style="height: 30px">
                        <ul>
                            <li class="col-sm-3" style="width: 33%">
                                <label>物料号：</label>
                                <input name="materialCode" type="text" id="materialCode" placeholder="物料号"
                                       class="form-control">
                            </li>
                            <li class="col-sm-3" style="width: 33%">
                                <label>物料描述：</label>
                                <input name="materialDesc" type="text" id="materialDesc" class="form-control"
                                       placeholder="物料描述">
                            </li>
                            <li class="col-sm-3" style="width: 33%">
                                <button id="ordelSearchBtn" type="button" class="btn btn-primary btn-rounded btn-sm"><i
                                        class="fa fa-search"></i>&nbsp;搜索
                                </button>
                                <button class="btn btn-warning btn-rounded btn-sm" type="reset"><i
                                        class="fa fa-eraser"></i>&nbsp;重置
                                </button>
                            </li>
                        </ul>
                    </div>
                    <table class="table table-bordered text-nowrap" id="ordel">

                    </table>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick='check_form("ordel")'>确定</button>
            </div>
        </div>

    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<!-- 指定报价的供应商 -->
<div class="modal fade" id="myModalVendor" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document" style="width:70%">
        <div class="modal-content" style="height:700px">
            <form id="inquiryVendorForm" th:action="@{/inquiryQuotation/list}" class="form-inline">
                <!-- <input type="hidden" name="vendorCode" id="vendorCode" /> -->
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">供应商报价信息</h4>
                </div>
                <div class="modal-body" style="height:90%;width:85%;overflow:auto">

                    <div style="height: 30px;width:100%">
                        <ul>
                            <li class="col-sm-3" style="width: 40%">
                                <label style="width: 100px">供应商编码：</label>
                                <input name="vendorCode" type="text" id="vendorCode" placeholder="供应商编码"
                                       class="form-control">
                            </li>
                            <li class="col-sm-3" style="width: 40%">
                                <label style="width: 120px">供应商名称：</label>
                                <input name="vendorName" type="text" id="vendorName" class="form-control"
                                       placeholder="供应商名称">
                            </li>
                            <li class="col-sm-3" style="width: 20%">
                                <button id="inquiryVendorSearchBtn" type="button"
                                        class="btn btn-primary btn-rounded btn-sm"><i class="fa fa-search"></i>&nbsp;搜索
                                </button>
                                <button class="btn btn-warning btn-rounded btn-sm" type="reset"><i
                                        class="fa fa-eraser"></i>&nbsp;重置
                                </button>
                            </li>
                        </ul>
                    </div>
                    <table class="table table-bordered text-nowrap" id="inquiryVendor">

                    </table>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick='check_form("inquiryVendor")'>确定</button>
            </div>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

<!--引入公共js-->
<div th:include="common/onload_js :: onloadJS"></div>
<!-- Chosen -->
<script th:src="@{/static/js/plugins/chosen/chosen.jquery.js}"></script>
<!-- <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> -->
<script th:inline="javascript">

    $(function () {
        var vendorInfoEntitylist = [[${vendorInfoEntitylist}]];
        vendorInfoEntitylist = eval('(' + vendorInfoEntitylist + ')');
        var gysmcs = [];
        var gysmcsOne = [];
        var gysmcsTwo = [];
        for (var i = 0; i < vendorInfoEntitylist.length; i++) {
            if ((vendorInfoEntitylist[i].vendorName)) {
                gysmcs.push(vendorInfoEntitylist[i].vendorName);
            }
            if ((vendorInfoEntitylist[i].vendorCode)) {
                //gysmcs.push(vendorInfoEntitylist[i].vendorCode);
                gysmcsOne.push(vendorInfoEntitylist[i].vendorCode);
            }
            if ((vendorInfoEntitylist[i].taxCode)) {
                gysmcsTwo.push(vendorInfoEntitylist[i].taxCode);
            }
        }
        $('#vendorName').autoComplete({
            minChars: 1,
            width: 320,
            source: function (term, suggest) {
                var choices = gysmcs;
                var suggestions = [];
                for (i = 0; i < choices.length; i++) {
                    if (choices[i].indexOf(term) >= 0) {
                        suggestions.push(choices[i]);
                    }
                }
                suggest(suggestions);
            }
        });

        $('#vendorCode').autoComplete({
            minChars: 1,
            width: 320,
            source: function (term, suggestOne) {
                var choicesOne = gysmcsOne;
                var suggestionsOne = [];
                for (i = 0; i < choicesOne.length; i++) {
                    if (choicesOne[i].indexOf(term) >= 0) {
                        suggestionsOne.push(choicesOne[i]);
                    }
                }
                suggestOne(suggestionsOne);
            }
        });
        $('#taxCode').autoComplete({
            minChars: 1,
            width: 320,
            source: function (term, suggest) {
                var choices = gysmcsTwo;
                var suggestionsTwo = [];
                for (i = 0; i < choices.length; i++) {
                    if (choices[i].indexOf(term) >= 0) {
                        suggestionsTwo.push(choices[i]);
                    }
                }
                suggest(suggestionsTwo);
            }
        });
    });


    function deletetr(tdobject) {
        var td = $(tdobject);
        td.parents("tr").remove();
    }

    // 初始化时间插件
    laydate.render({elem: '#requestDate'});
    laydate.render({elem: '#deliveryDate'});

    initDictDataSel();//初始化所有字典数据
    //查询
    function fun(obj) {
        $("#materialCode").val(obj.value);
        Searcher.createBS('#ordel',
            [
                {radio: true},
                {title: "供应商编码", field: "vendorCode"},
                {title: "含税单价", field: "poPrice"},
                {title: "价格单位", field: "priceUnit"},
                {title: "币种", field: "currencyCode"},
                {title: "税码", field: "taxCode"},
                {title: "采购单号", field: "prNo"},
                {title: "工厂", field: "factory"},
                {title: "物料编码", field: "materialCode"},
                {title: "物料描述", field: "materialDesc"}
            ], {pageList: [10], pageSize: 10, showColumns: false, showRefresh: false}
        );
    }

    var id;

    function show(obj) {
        id = $(obj).attr("indexval");
        var td_vendorCode = $("#vendorCode").attr("id");
        var td_vendorName = $("#vendorName").attr("id");
        var td_taxPrice = $("#taxPrice").attr("id");
        var td_priceUnit = $("#priceUnit").attr("id");
        var td_currency = $("#currency").attr("id");
        var td_taxCode = $("#taxCode").attr("id");

        var td_purchRequestCode = $("#").attr("id")
        $("#vendorCode").attr('id', td_vendorCode + id);
        $("#vendorName").attr('id', td_vendorName + id);
        $("#taxPrice").attr('id', td_taxPrice + id);
        $("#priceUnit").attr('id', td_priceUnit + id);
        $("#currency").attr('id', td_currency + id);
        $("#taxCode").attr('id', td_taxCode + id);

        Searcher.createBS('#inquiryVendor',
            [
                {radio: true},
                {title: "供应商编码", field: "vendorCode"},
                {title: "供应商名称", field: "vendorName"},
                {title: "含税单价", field: "price"},
                {title: "公司代码", field: "compCode"},
                {title: "价格单位", field: "priceUnit"},
                {title: "币种", field: "currency"},
                {title: "税码", field: "taxCode"}
            ], {pageList: [10], pageSize: 10, showColumns: false, showRefresh: false}
        );
    }

    function check_form(obj) {
        //使用getSelections即可获得，row是json格式的数据
        var rows = $("#" + obj).bootstrapTable('getSelections');
        //判断是否选中行
        if (!rows || rows.length == 0) {
            Dialog.alert("请先选中一行！")
            return;
        }
        showTableData(rows[0], obj);
    }

    function showTableData(json, obj) {
        if ("inquiryVendor" == obj) {
            //$("#vendor_table").bootstrapTable('removeAll');
            $("#para_table td input[id='vendorCode" + id + "']").val(json.vendorCode);
            $("#para_table td input[id='vendorName" + id + "']").val(json.vendorName);
            $("#para_table td input[id='taxPrice" + id + "']").val(json.price);
            $("#para_table td input[id='priceUnit" + id + "']").val(json.priceUnit);
            $("#para_table td input[id='currency" + id + "']").val(json.currency);
            $("#para_table td select[id='taxCode" + id + "']").val(json.taxCode);
            $('#myModalVendor').modal('hide');
        }
        if ("ordel" == obj) {
            //$("#para_table").bootstrapTable('removeAll');
            $("#para_table td input[id='vendorCode" + id + "']").val(json.vendorCode);
            $("#para_table td input[id='vendorName" + id + "']").val(json.vendorName);
            $("#para_table td input[id='taxPrice" + id + "']").val(json.poPrice);
            $("#para_table td input[id='priceUnit" + id + "']").val(json.priceUnit);
            $("#para_table td input[id='currency" + id + "']").val(json.currencyCode);
            $("#para_table td select[id='taxCode" + id + "']").val(json.taxCode);
            $('#myModalGoods').modal('hide');
        }
    }

    /**
     * 封装并提交数据
     **/
    function save() {

        //判断价格是否为空
        let flag = false;
        $("input[name='taxPrice']").each(function (index, item) {
            if ($(item).val() == null || $(item).val().trim() == '') {
                Dialog.errorMsg("请填写价格！");
                flag = true;
                return false;
            }
        })
        //价格为空，返回
        if (flag) {
            return false;
        }
        var subjectCategory = $("#subjectCategory").val();
        if (subjectCategory == "K") {
            var internalOrderCode = $("#internalOrderCode").val();
            console.log(internalOrderCode.length);
            if (internalOrderCode.length != 0) {
                Dialog.errorMsg("订单类型K不能填写内部订单号，请退回采购申请重新确！");
                return false;
            }
        }

        var purchRequestCode = $("input[name='purchRequestCode']").first().val();
        var data = {"purchRequestCodetem": purchRequestCode, "supplyGoodsEntity": []};//先定义数据结构，head是一个对象，item是一个数组
        //得到行项目数据
        var trs = $("#para_table").find("tr");
        trs.each(function (index, tr) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
            var itemEntity = {};
            var SupplyGoodsEntityVO = {};
            var its = $(tr).find("input, select");
            its.each(function (idx, it) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
                SupplyGoodsEntityVO[$(it).attr("name")] = $(it).val();
            });
            if (JSON.stringify(SupplyGoodsEntityVO) != "{}") {
                itemEntity["SupplyGoodsEntityVO"] = SupplyGoodsEntityVO;
                data.supplyGoodsEntity.push(itemEntity);
            }
        });
        layer.load(1, {shade: [0.3, '#393D49']});
        $.ajax({
            type: "POST",
            url: ctxPath + "/nproPurchRequestHeader/updateSource",
            data: JSON.stringify(data),//必须
            contentType: "application/json;charsetset=UTF-8",//必须
            dataType: "json",//必须
            cache: true,
            async: true,
            success: function (res) {
                alert("订单号已经生成：" + res["poNo"]);
                parent.itemBS.refresh();
                layer.closeAll();
                Dialog.closeFrame(window.name);
            },
            error: function (request) {
                layer.closeAll();
                showTipAlert("Connection error");
            }
        });
        parent.itemBS.refresh();
    }


</script>

</body>
</html>
